<template>
  <div class="edit-app-page">
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="text" 
          @click="goBack"
          class="back-button"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <div class="header-info">
          <h1>{{ isEdit ? '编辑应用' : '创建应用' }}</h1>
          <p class="page-description">
            {{ isEdit ? '修改应用的基本信息' : '创建新的应用' }}
          </p>
        </div>
      </div>
    </div>

    <div class="form-container">
      <el-card>
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="app-form"
        >
          <el-form-item label="应用名称" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入应用名称"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="应用描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="4"
              placeholder="请输入应用描述或初始提示词"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <!-- 管理员专用字段 -->
          <template v-if="isAdmin">
            <el-form-item label="应用封面" prop="coverImage">
              <div class="cover-upload">
                <el-upload
                  class="cover-uploader"
                  :show-file-list="false"
                  :before-upload="beforeCoverUpload"
                  :http-request="uploadCover"
                  accept="image/*"
                >
                  <img v-if="formData.coverImage" :src="formData.coverImage" class="cover-image" />
                  <div v-else class="cover-placeholder">
                    <el-icon class="cover-icon"><Plus /></el-icon>
                    <div class="cover-text">上传封面</div>
                  </div>
                </el-upload>
                <div class="cover-tips">
                  <p>建议尺寸：400x300像素</p>
                  <p>支持格式：JPG、PNG、GIF</p>
                  <p>文件大小：不超过2MB</p>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="优先级" prop="priority">
              <el-input-number
                v-model="formData.priority"
                :min="0"
                :max="99"
                placeholder="请输入优先级"
              />
              <div class="priority-tips">
                <p>优先级越高，应用在列表中的排序越靠前</p>
                <p>设置为99表示精选应用</p>
              </div>
            </el-form-item>

            <el-form-item label="应用状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择状态">
                <el-option label="正常" value="normal" />
                <el-option label="精选" value="featured" />
                <el-option label="已部署" value="deployed" />
                <el-option label="已禁用" value="disabled" />
              </el-select>
            </el-form-item>
          </template>

          <!-- 应用信息展示（只读） -->
          <template v-if="isEdit">
            <el-form-item label="创建者">
              <el-input v-model="formData.creator" readonly />
            </el-form-item>

            <el-form-item label="创建时间">
              <el-input :value="formatDateTime(formData.createTime)" readonly />
            </el-form-item>

            <el-form-item label="更新时间">
              <el-input :value="formatDateTime(formData.updateTime)" readonly />
            </el-form-item>
          </template>

          <el-form-item class="form-actions">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              {{ isEdit ? '保存修改' : '创建应用' }}
            </el-button>
            <el-button @click="resetForm">
              重置
            </el-button>
            <el-button @click="goBack">
              取消
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="应用预览"
      width="600px"
    >
      <div class="app-preview">
        <div class="preview-item">
          <label>应用名称：</label>
          <span>{{ formData.name || '未设置' }}</span>
        </div>
        <div class="preview-item">
          <label>应用描述：</label>
          <p>{{ formData.description || '未设置' }}</p>
        </div>
        <div class="preview-item" v-if="formData.coverImage">
          <label>应用封面：</label>
          <img :src="formData.coverImage" class="preview-cover" />
        </div>
        <div class="preview-item" v-if="isAdmin">
          <label>优先级：</label>
          <span>{{ formData.priority }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Plus } from '@element-plus/icons-vue'
import { appApi } from '@/api'
import { useUserStore } from '@/stores/user'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 表单引用
const formRef = ref(null)

// 计算属性
const isEdit = computed(() => !!route.params.id)
const isAdmin = computed(() => userStore.userInfo?.role === 'admin')
const appId = computed(() => route.params.id)

// 表单数据
const formData = reactive({
  name: '',
  description: '',
  coverImage: '',
  priority: 0,
  status: 'normal',
  creator: '',
  createTime: null,
  updateTime: null
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入应用名称', trigger: 'blur' },
    { min: 1, max: 50, message: '应用名称长度在1到50个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入应用描述', trigger: 'blur' },
    { min: 1, max: 500, message: '应用描述长度在1到500个字符', trigger: 'blur' }
  ]
}

// 状态
const submitLoading = ref(false)
const previewDialogVisible = ref(false)

// 初始化
onMounted(async () => {
  if (isEdit.value) {
    await loadAppInfo()
  }
})

// 加载应用信息
const loadAppInfo = async () => {
  try {
    const response = await appApi.getAppById(appId.value)
    if (response.code === 0) {
      Object.assign(formData, response.data)
    } else {
      ElMessage.error(response.message || '加载应用信息失败')
      goBack()
    }
  } catch (error) {
    console.error('加载应用信息失败:', error)
    ElMessage.error('加载应用信息失败')
    goBack()
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 权限检查
    if (isEdit.value && !isAdmin.value && formData.creator !== userStore.userInfo?.username) {
      ElMessage.error('您只能编辑自己创建的应用')
      return
    }
    
    submitLoading.value = true
    
    let response
    if (isEdit.value) {
      // 更新应用
      response = await appApi.updateApp(appId.value, formData)
    } else {
      // 创建应用
      response = await appApi.createApp(formData)
    }
    
    if (response.code === 0) {
      ElMessage.success(isEdit.value ? '保存成功' : '创建成功')
      
      if (!isEdit.value) {
        // 新创建的应用，询问是否进入对话页面
        try {
          await ElMessageBox.confirm(
            '应用创建成功！是否立即开始与AI对话生成网站？',
            '创建成功',
            {
              confirmButtonText: '开始对话',
              cancelButtonText: '稍后再说',
              type: 'success'
            }
          )
          
          // 跳转到对话页面
          router.push({
            name: 'ChatPage',
            params: { id: response.data.id },
            query: { autoStart: 'true' }
          })
        } catch {
          // 用户选择稍后再说，返回上一页
          goBack()
        }
      } else {
        goBack()
      }
    } else {
      ElMessage.error(response.message || (isEdit.value ? '保存失败' : '创建失败'))
    }
  } catch (error) {
    if (error !== 'validation failed') {
      console.error('提交失败:', error)
      ElMessage.error(isEdit.value ? '保存失败' : '创建失败')
    }
  } finally {
    submitLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  if (isEdit.value) {
    loadAppInfo()
  } else {
    Object.assign(formData, {
      name: '',
      description: '',
      coverImage: '',
      priority: 0,
      status: 'normal'
    })
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 封面上传前检查
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

// 上传封面
const uploadCover = async (options) => {
  const { file } = options
  
  try {
    // 这里应该调用实际的文件上传接口
    // 暂时使用本地预览
    const reader = new FileReader()
    reader.onload = (e) => {
      formData.coverImage = e.target.result
    }
    reader.readAsDataURL(file)
    
    ElMessage.success('封面上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 格式化日期时间
const formatDateTime = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.edit-app-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-header {
  background: white;
  padding: 16px 24px;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-button {
  padding: 8px;
  font-size: 16px;
}

.header-info h1 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.form-container {
  max-width: 800px;
  margin: 24px auto;
  padding: 0 24px;
}

.app-form {
  padding: 20px;
}

.cover-upload {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-image {
  width: 200px;
  height: 150px;
  object-fit: cover;
  display: block;
}

.cover-placeholder {
  width: 200px;
  height: 150px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8c939d;
  background-color: #fafafa;
}

.cover-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.cover-text {
  font-size: 14px;
}

.cover-tips {
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.cover-tips p {
  margin: 0 0 4px 0;
}

.priority-tips {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.priority-tips p {
  margin: 0 0 4px 0;
}

.form-actions {
  margin-top: 32px;
  text-align: center;
}

.app-preview {
  padding: 0;
}

.preview-item {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.preview-item label {
  font-weight: 600;
  color: #303133;
  min-width: 80px;
  flex-shrink: 0;
}

.preview-item span,
.preview-item p {
  margin: 0;
  color: #606266;
  flex: 1;
}

.preview-cover {
  max-width: 200px;
  max-height: 150px;
  object-fit: cover;
  border-radius: 4px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-container {
    margin: 16px;
    padding: 0;
  }
  
  .page-header {
    padding: 12px 16px;
  }
  
  .header-left {
    gap: 12px;
  }
  
  .cover-upload {
    flex-direction: column;
    gap: 12px;
  }
  
  .cover-image,
  .cover-placeholder {
    width: 100%;
    max-width: 300px;
  }
  
  .preview-item {
    flex-direction: column;
    gap: 4px;
  }
  
  .preview-item label {
    min-width: auto;
  }
}
</style>